package service.impl;

import dao.UserDAO;
import dao.impl.UserDAOImpl;
import pojo.UserDO;
import service.UserServise;

public class UserServiseImpl implements UserServise {
    private UserDAO userDAO=new UserDAOImpl();

    /**
     * 根据用户名和密码查询用户
     * @param username
     * @param pwd
     * @return
     */
    @Override
    public UserDO getUser(String username, String pwd) {
        return userDAO.getUser(username,pwd);
    }

    /**
     * 根据id查询用户
     * @param name
     * @return
     */
    @Override
    public UserDO getUser(String name) {
        return userDAO.getUser(name);
    }

    /**
     * 存钱
     * @param name
     * @param money
     */
    @Override
    public void depositMoney(String name, Double money) {
        UserDO userDO=userDAO.getUser(name);
        userDO.setMoney(userDO.getMoney()+money);
        userDAO.update(userDO);
    }

    /**
     * 取钱
     * @param name
     * @param money
     * @throws Exception
     */
    @Override
    public void getMoney(String name, Double money) throws Exception {
        UserDO userDO=userDAO.getUser(name);
        if (userDO.getMoney()<money){
            throw new Exception("余额不足");
        }
        userDO.setMoney(userDO.getMoney()-money);
        userDAO.update(userDO);
    }
    public void transfer(String saveName,String getNmae,Double money) throws NullPointerException,Exception,RuntimeException{
        UserDO saveUser=userDAO.getUser(saveName);
        UserDO getUser=userDAO.getUser(getNmae);
        if (saveUser==null){
            throw new NullPointerException("查无此人");
        }
        if (saveUser.getId().equals(getUser.getId())){
            throw new RuntimeException("不能向自己转账");
        }
        if (getUser.getMoney()<money){
            throw new Exception("余额不足");
        }
        saveUser.setMoney(saveUser.getMoney()+money);
        getUser.setMoney(getUser.getMoney()-money);
        userDAO.update(saveUser);
        userDAO.update(getUser);
    }
}
